from flask import Flask, request, jsonify
import os, requests
import redis
import logging
from logging.handlers import RotatingFileHandler
from logging import Formatter


app = Flask(__name__)
app.logger.setLevel(logging.INFO)

# class CustomFormatter(Formatter):
#     def format(self, record):
#         record.message = record.getMessage().replace(" ", "<br>")
#         return super().format(record)
# log_file = "/opt/logs/file.log"  # 日志文件路径
# file_handler = RotatingFileHandler(
#     log_file, maxBytes=1024 * 1024 * 5, backupCount=5
# )  # 创建文件处理器，最多5MB，最多备份5个文件
# file_handler.setFormatter(CustomFormatter())  # 设置自定义格式化器
# app.logger.addHandler(file_handler)  # 将文件处理器添加到Logger对象中


pool = redis.ConnectionPool(host="redisdb", port=6379, decode_responses=True)


def doGetRequset(appid, secret):
    """发起微信小程序请求"""
    url = "https://api.weixin.qq.com/cgi-bin/token"
    params = {"grant_type": "client_credential", "appid": appid, "secret": secret}
    res = requests.get(url, params=params)
    res.encoding = "utf-8"
    if not res.status_code == 200:
        return False
    token = res.json()
    r = redis.Redis(connection_pool=pool)
    r.set(appid, token.get("access_token"), ex=token.get("expires_in"))
    return token.get("access_token")


@app.route("/")
def hello_world():
    app.logger.info("访问首页")
    return """Hello, World!<br> 
        This is a Api for SwapToken.<br> 
        headers['authkey'] = 'xxxx'<br> 
        url = '/upload'<br>
        <a href='/web'>try</a>
    """


@app.route("/web")
def index():
    return """
    <h1>has AccessToken</h1>
    <form method="get" action="/hasToken" enctype="multipart/form-data">
        <input type="text" name="appid" /><br><hr><input type="text" name="secret" /><br><hr>
        <input type="submit" value="Upload" /><hr>
    </form>
"""


@app.route("/hasToken")
def getAccessToken():
    """获取微信小程序接口调用凭据"""
    appid = request.args.get("appid")
    secret = request.args.get("secret")
    if not appid or not secret:
        return jsonify({"msg": "拒绝服务", "code": 1})
    r = redis.Redis(connection_pool=pool)
    token = r.get(appid) or doGetRequset(appid, secret)
    return jsonify({"msg": token, "code": 0})
